package org.dromara.module.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vdurmont.emoji.EmojiParser;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.TransactionalException;
import org.dromara.common.core.exception.YshopException;
import org.dromara.common.core.utils.QRCodeUtilEx;
import org.dromara.common.core.utils.RegexUtil;
import org.dromara.common.core.utils.file.FileUploadUtils;
import org.dromara.module.domain.*;
import org.dromara.module.domain.dto.*;
import org.dromara.module.mapper.*;
import org.dromara.module.service.*;
import org.dromara.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品Service业务层处理
 *
 * @author Mr.Zhou
 * @date 2024-10-21
 */
@RequiredArgsConstructor
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Resource
    private IProductAttrValueService productAttrValueService;
    @Resource
    private IProductAttrService productAttrService;
    @Resource
    private ProductAttrMapper productAttrMapper;
    @Resource
    private ProductAttrValueMapper productAttrValueMapper;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private ProductImgMapper productImgMapper;
    @Resource
    private IProductRuleService productRuleService;
    @Resource
    private ISysDictDataService sysDictDataService;
    @Resource
    private IProductOrderInfoService productOrderInfoService;
    @Resource
    private ProductTypeMapper productTypeMapper;
    private final IProductImgService productImgService;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;

//	@Value("${ruoyi.imgUrlOss}")
//	private String imgUrlOss;

    @Override
    @Transactional
    public int addProduct(Product product) throws TransactionalException {
        try{
            if(StrUtil.isNotEmpty(product.getDescription())){
                String content = EmojiParser.parseToAliases(product.getDescription());
                String description = RegexUtil.convertProductDescription(content);
                System.out.println("description : " + description);
                product.setDescription(description);
            }

            if(StrUtil.isNotEmpty(product.getBuyingTips())){
                String buyTips = EmojiParser.parseToAliases(product.getBuyingTips());
                product.setBuyingTips(RegexUtil.convertProductDescription(buyTips));
            }

            //添加商品
            Product yxStoreProduct = new Product();
            BeanUtil.copyProperties(product, yxStoreProduct, "sliderImage");
            if (product.getProductImgLunbos() == null || product.getProductImgLunbos().isEmpty()) {
//				throw new YshopException("请上传轮播图");
                return -1;
            }

//            yxStoreProduct.setSliderImage(String.join(",", product.getSliderImage()));

            /**
             * 是否是销售类型的商品或服务  0 - 咨询类型 1 - 销售类型
             */
            if(product.getIsSale() == 1){
                ProductResultDto resultDTO = this.computedProduct(product.getAttrs());
                yxStoreProduct.setPrice(BigDecimal.valueOf(resultDTO.getMinPrice()));
                yxStoreProduct.setOtPrice(BigDecimal.valueOf(resultDTO.getMinOtPrice()));
                yxStoreProduct.setCost(BigDecimal.valueOf(resultDTO.getMinCost()));
                yxStoreProduct.setStock(resultDTO.getStock());
//				yxStoreProduct.setSi(resultDTO.getStock());
            }

            if (product.getId() != null) {
                //清空商品转发图
                deleteForwardImg(product.getId());
            }


//            Mer mer = merMapper.selectById(product.getMerId());
//            if(mer!= null){
//                if(mer.getShopType() == 8){//餐饮类
//                    ProductType productType = productTypeMapper.selectById(product.getCateId());
//                    if(productType!= null){
//                        product.setDishType(productType.getDishType());
//                    }
//                }
//            }
            boolean bl = this.saveOrUpdate(yxStoreProduct);
            if(bl){
                QueryWrapper<ProductImg> qwImg = new QueryWrapper<>();
                qwImg.eq("product_id",yxStoreProduct.getId());
                qwImg.eq("img_type", 0);
                ProductImg proImg = productImgMapper.selectOne(qwImg);
                if(proImg!=null){
                    if(CollUtil.isNotEmpty(product.getProductImgs())){
                        if(product.getProductImgs().size() > 0) {
                            proImg.setImgUrl(product.getProductImgs().get(0).getImgUrl());
                            productImgMapper.updateById(proImg);
                        }
                    }
                }else{
                    if(CollUtil.isNotEmpty(product.getProductImgs())){
                        if(product.getProductImgs().size() > 0){
                            proImg = new ProductImg();
                            proImg.setProductId(yxStoreProduct.getId());
                            proImg.setImgUrl(product.getProductImgs().get(0).getImgUrl());
                            proImg.setSort(0);
                            proImg.setImgType(0);
                            productImgMapper.insert(proImg);
                        }
                    }
                }


                List<ProductImg> delImg = new ArrayList<>();
                List<ProductImg> imgs = product.getProductImgLunbos();

                QueryWrapper<ProductImg> qw = new QueryWrapper<>();
                qw.eq("product_id",yxStoreProduct.getId());
                qw.eq("img_type", 1);
                List<ProductImg> productImgs = productImgMapper.selectList(qw);
                if(CollUtil.isNotEmpty(productImgs)){
                    for (ProductImg img : productImgs){
                        int isHas = 0;
                        for (ProductImg img1 : imgs){
                            if (img1.getId() != null && img.getId().equals(img1.getId())) {//存在
                                isHas = 1;
                                break;
                            }
                        }
                        if(isHas == 0){
                            delImg.add(img);
                        }
                    }
                }

                if(CollUtil.isNotEmpty(imgs)){
                    for (ProductImg img : imgs){
                        if(img.getId() == null){
                            img.setProductId(yxStoreProduct.getId());
                            img.setSort(1);
                            img.setImgType(1);
                            productImgMapper.insert(img);
                        }
                    }
                }
                if(CollUtil.isNotEmpty(delImg)){
                    for (ProductImg img : delImg){
                        productImgMapper.deleteById(img.getId());
                    }
                }

                if(StrUtil.isEmpty(yxStoreProduct.getProductNo())){
                    String no = String.valueOf(2200000 + yxStoreProduct.getId());
                    yxStoreProduct.setProductNo(no);
                }
            }

            if(product.getIsSale() == 1) {
                //属性处理
                //处理单sKu
                if (product.getSpecType() == 0) {// 单规格
                    FromatDetailDto fromatDetailDto = FromatDetailDto.builder()
                        .value("规格").detailValue("")
                        .attrHidden("")
                        .detail(ListUtil.toList("默认"))
                        .build();
                    List<ProductFormatDto> attrs = product.getAttrs();
                    ProductFormatDto productFormatDto = attrs.get(0);
                    productFormatDto.setValue1("规格");
                    Map<String, String> map = new HashMap<>();
                    map.put("规格", "默认");
                    productFormatDto.setDetail(map);
                    productAttrService.insertProductAttr(ListUtil.toList(fromatDetailDto), ListUtil.toList(productFormatDto), yxStoreProduct.getId());
                } else {
                    //多规格的 去掉默认规格的
                    QueryWrapper<ProductAttr> qw = new QueryWrapper<>();
                    qw.eq("product_id",yxStoreProduct.getId());
                    qw.eq("attr_name", "规格");
                    qw.eq("attr_values", "默认");
                    ProductAttr productAttr = productAttrService.getOne(qw);
                    if(productAttr != null){
                        productAttrService.removeById(productAttr.getId());
                    }
                    //多规格
                    productAttrService.insertProductAttr(product.getItems(), product.getAttrs(), yxStoreProduct.getId());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("addProduct system erro");
        }
        return 1;
    }

    /**
     * 商品详情
     *
     * @param id        商品id
     * @return ProductVo
     */
    @Override
    public Product goodsDetail(Long id) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getId, id);
        Product product = productMapper.selectOne(wrapper);
        if (ObjectUtil.isNull(product)) {
            return null;
        }


        if(StrUtil.isNotEmpty(product.getImage())){
            if(product.getImage().indexOf("https") < 0){
                product.setImagePath(imgUrl + product.getImage());
            }else{
                product.setImagePath(product.getImage());
            }
        }else{
            product.setImagePath("");
        }


        List<String> sliderImageArray = new ArrayList<>();
        String sliderImgs = "";
        product.setSliderImageArray(sliderImageArray);
        if(StrUtil.isNotEmpty(product.getSliderImage())){
            String[] sliderImages = product.getSliderImage().split(",");
            for (String img: sliderImages){
                if(img.indexOf("https") < 0){
                    sliderImageArray.add(imgUrl + img);
                    sliderImgs += imgUrl + img + ",";
                }else{
                    sliderImageArray.add(img);
                    sliderImgs += img + ",";
                }
            }
            if(sliderImgs.length() > 0){
                sliderImgs = sliderImgs.substring(0,sliderImgs.length() - 1);
            }
            product.setSliderImagePath(sliderImgs);
            product.setSliderImageArray(sliderImageArray);
        }





        if(StrUtil.isNotEmpty(product.getDescription())){
            product.setDescription(EmojiParser.parseToUnicode(product.getDescription()));
        }

        if(StrUtil.isNotEmpty(product.getBuyingTips())){
            product.setBuyingTips(EmojiParser.parseToUnicode(product.getBuyingTips()));
        }

        //获取商品sku
        Map<String, Object> returnMap = productAttrService.getProductAttrDetail(id);

        ProductRule rule = productRuleService.getOne(new LambdaQueryWrapper<ProductRule>().eq(ProductRule::getId, product.getRuleId()));
        if(rule != null){
            if(StrUtil.isNotEmpty(rule.getRuleValue())){

                rule.setRuleValueArray(JSONUtil.parseArray(rule.getRuleValue()));
            }
        }
        product.setRule(rule);


        //设置商品相关信息
        product.setProductAttr((List<ProductAttr>) returnMap.get("productAttr"));
        product.setProductValue((Map<String, ProductAttrValue>) returnMap.get("productValue"));

        return product;
    }

    @Override
    public List<Product> queryProductList(WxUser user, String productName, int typeId, int typeChildId, int pageIndex, int pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("is_show", 1);
        map.put("is_del", 0);
        QueryWrapper<Product> qw = new QueryWrapper<>();
        qw.eq("is_show",1);
        qw.eq("is_del",0);
        if(typeId > 0){
            qw.eq("cate_id", typeId);
            map.put("cate_id", typeId);
        }
        if(typeChildId > 0){
            qw.eq("cate_child_id", typeChildId);
            map.put("cate_child_id", typeChildId);
        }

        if(StrUtil.isNotEmpty(productName)){
            qw.like("product_name", productName);
            map.put("product_name", productName);
        }
        qw.orderByAsc("sort");
        List<Product> listNew = new ArrayList<>();
//        selectPageList
//        Page<Product> page = new Page<>();
//        page.setCurrent(pageIndex);
//        page.setSize(pageSize);
//        List<Product> list = productMapper.getPageEntityList(qw, pageIndex, pageSize);
        int offset = (pageIndex - 1) * pageSize;
        List<Product> list = productMapper.selectPageList(map, offset, pageSize);
        if (list != null && list.size() > 0){
            for (Product product : list){
                product = getProductInfoById(product.getId());
                listNew.add(product);
            }
        }
        return listNew;
    }


    @Override
    public Product getProductByOrderId(Long orderId) {
        Product product = null;
        ProductOrderInfo orderInfo = productOrderInfoService.selectOneByOrderId(orderId);
        if(orderInfo!=null){
            product = productMapper.selectById(orderInfo.getProductId());
        }
        return product;
    }

    @Override
    public Product getProductInfoById(Long id) {
        Product product = productMapper.selectById(id);
        if(product != null){
            if(StrUtil.isNotEmpty(product.getImage())){
                if(product.getImage().indexOf("http") < 0){
                    product.setImage(imgUrl + product.getImage());
                }
            }

            List<String> sliderImageArray = new ArrayList<>();
            String sliderImgs = "";
            product.setSliderImageArray(sliderImageArray);
            if(StrUtil.isNotEmpty(product.getSliderImage())){
                String[] sliderImages = product.getSliderImage().split(",");
                for (String img: sliderImages){
                    if(img.indexOf("http") < 0){
                        sliderImageArray.add(imgUrl + img);
                        sliderImgs += imgUrl + img + ",";
                    }else{
                        sliderImageArray.add(img);
                        sliderImgs += img + ",";
                    }
                }
                if(sliderImgs.length() > 0){
                    sliderImgs = sliderImgs.substring(0,sliderImgs.length() - 1);
                }
                product.setSliderImage(sliderImgs);
                product.setSliderImageArray(sliderImageArray);
            }


            String lunboImgs = "";
            List<String> lunboImgsArray = new ArrayList<>();
            QueryWrapper<ProductImg> qwLunbo = new QueryWrapper<>();
            qwLunbo.eq("product_id",product.getId());
            qwLunbo.eq("img_type",1);
            List<ProductImg> lunbos = productImgService.list(qwLunbo);
            for (ProductImg img : lunbos){
                if(StrUtil.isNotEmpty(img.getImgUrl())) {
                    lunboImgs += imgUrl + img.getImgUrl() + ",";
                    img.setImgUrlPath(imgUrl + img.getImgUrl());
                    lunboImgsArray.add(imgUrl + img.getImgUrl());
                }
            }
            product.setProductImgLunbos(lunbos);
            product.setSliderImageArray(lunboImgsArray);

            if(StrUtil.isNotEmpty(lunboImgs)){
                lunboImgs = lunboImgs.substring(0,lunboImgs.length() - 1);
            }

            product.setSliderImagePath(lunboImgs);


            List<ProductAttr> storeProductAttrs = productAttrMapper.selectList(Wrappers.<ProductAttr>lambdaQuery()
                .eq(ProductAttr::getProductId,product.getId())
                .orderByAsc(ProductAttr::getAttrValues));

            int totalCount = 0;
            List<ProductAttrValue> productAttrValues = productAttrValueMapper.selectList(
                Wrappers.<ProductAttrValue>lambdaQuery().eq(ProductAttrValue::getProductId,product.getId()).eq(ProductAttrValue::getIsDel,0));
            if(CollUtil.isNotEmpty(productAttrValues)){
                for (ProductAttrValue value : productAttrValues){
//                    value.setSku()
                    totalCount += value.getStock();
                    if(StrUtil.isNotEmpty(value.getImage())){
                        if(value.getImage().indexOf("http") < 0){
                            value.setImage(imgUrl + value.getImage());
                        }else{
                            value.setImage(value.getImage());
                        }
                    }else{
                        value.setImage("");
                    }
                }
                product.setTotalCount(totalCount);
            }

            List<ProductAttr> productAttrList = new ArrayList<>();
            for (ProductAttr attr : storeProductAttrs) {
                List<String> stringList = Arrays.asList(attr.getAttrValues().split(","));
                List<AttrValueDto> attrValueDTOS = new ArrayList<>();
                for (String str : stringList) {
                    AttrValueDto attrValueDTO = new AttrValueDto();
                    attrValueDTO.setAttr(str);
                    attrValueDTOS.add(attrValueDTO);
                }
                attr.setAttrValue(attrValueDTOS);
                attr.setAttrValueArr(stringList);
                productAttrList.add(attr);
            }

            Map<String, ProductAttrValue> map = productAttrValues.stream().collect(Collectors.toMap(ProductAttrValue::getSku, p -> p));
            product.setProductValue(map);

            product.setProductAttr(productAttrList);
        }
        return product;
    }

    @Override
    public void deleteForwardImg(Long id) {
//		baseMapper.deleteForwardImg(id, "_product_detail_wap");
    }


    /**
     * 计算产品数据
     *
     * @param attrs attrs
     * @return ProductResultDto
     */
    private ProductResultDto computedProduct(List<ProductFormatDto> attrs) {
        //取最小价格
        Double minPrice = attrs
            .stream()
            .map(ProductFormatDto::getPrice)
            .min(Comparator.naturalOrder())
            .orElse(0d);

        Double minOtPrice = attrs
            .stream()
            .map(ProductFormatDto::getOtPrice)
            .min(Comparator.naturalOrder())
            .orElse(0d);

        //计算库存
        Integer singleCount = attrs
            .stream()
            .map(ProductFormatDto::getSingleCount)
            .min(Comparator.naturalOrder())
            .orElse(0);

        Double minCost = attrs
            .stream()
            .map(ProductFormatDto::getCost)
            .min(Comparator.naturalOrder())
            .orElse(0d);
        //计算库存
        Integer stock = attrs
            .stream()
            .map(ProductFormatDto::getStock)
            .reduce(Integer::sum)
            .orElse(0);


        if (stock <= 0) {
            throw new YshopException("库存不能低于0");
        }

        return ProductResultDto.builder()
            .minPrice(minPrice)
            .minOtPrice(minOtPrice)
            .minCost(minCost)
            .stock(stock)
            .singleCount(singleCount)
            .build();
    }


    /**
     * 获取生成的属性
     *
     * @param id      商品id
     * @param jsonStr jsonStr
     * @return map
     */
    @Override
    public Map<String, Object> getFormatAttr(Long id, String jsonStr, boolean isActivity,Integer isReset) {
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        Map<String, Object> resultMap = new LinkedHashMap<>(3);

        if (jsonObject == null || jsonObject.get("attrs") == null || jsonObject.getJSONArray("attrs").isEmpty()) {
            resultMap.put("attr", new ArrayList<>());
            resultMap.put("value", new ArrayList<>());
            resultMap.put("header", new ArrayList<>());
            return resultMap;
        }
        try{
            List<FromatDetailDto> fromatDetailDTOList = JSONUtil.toList(jsonObject.getStr("attrs"),FromatDetailDto.class);

            //fromatDetailDTOList
            DetailDto detailDto = this.attrFormat(fromatDetailDTOList);

            List<Map<String, Object>> headerMapList = null;
            List<Map<String, Object>> valueMapList = new ArrayList<>();
            String align = "center";
            Map<String, Object> headerMap = new LinkedHashMap<>();
            for (Map<String, Map<String, String>> map : detailDto.getRes()) {
                Map<String, String> detail = map.get("detail");
                String[] detailArr = detail.values().toArray(new String[]{});
                Arrays.sort(detailArr);
                String sku = String.join(",", detailArr);
                Map<String, Object> valueMap = new LinkedHashMap<>();
                List<String> detailKeys = detail.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toList());
                int i = 0;
                headerMapList = new ArrayList<>();
                for (String title : detailKeys) {
                    headerMap.put("title", title);
                    headerMap.put("minWidth", "120");
                    headerMap.put("align", align);
                    headerMap.put("key", "value" + (i + 1));
                    headerMap.put("slot", "value" + (i + 1));
                    headerMapList.add(ObjectUtil.clone(headerMap));
                    i++;
                }

                String[] detailValues = detail.values().toArray(new String[]{});
                for (int j = 0; j < detailValues.length; j++) {
                    String key = "value" + (j + 1);
                    valueMap.put(key, detailValues[j]);
                }

                valueMap.put("id", 0);
                valueMap.put("detail", detail);
//				valueMap.put("image", "");
//				valueMap.put("imagePath", "");
                valueMap.put("price", 0);
                valueMap.put("cost", 0);
                valueMap.put("otPrice", 0);
                valueMap.put("stock", 0);
                valueMap.put("singleCount", 1);
//				valueMap.put("barCode", "");
//				valueMap.put("weight", 0);
//				valueMap.put("volume", 0);
//				valueMap.put("brokerage", 0);
//				valueMap.put("brokerageTwo", 0);
//				valueMap.put("pinkPrice", 0);
//				valueMap.put("pinkStock", 0);
                if (id > 0) {
                    ProductAttrValue productAttrValue = productAttrValueService
                        .getOne(Wrappers.<ProductAttrValue>lambdaQuery()
                            .eq(ProductAttrValue::getProductId, id)
                            .eq(ProductAttrValue::getSku, sku)
                            .eq(ProductAttrValue::getIsDel, 0)
                            .last("limit 1"));
                    if (productAttrValue != null) {
                        valueMap.put("id", productAttrValue.getId());
//						valueMap.put("image", productAttrValue.getImage());
//						if(StrUtil.isNotEmpty(productAttrValue.getImage())){
//							if(productAttrValue.getImage().indexOf("http") < 0){
//								productAttrValue.setImagePath(imgUrl + productAttrValue.getImage());
//								valueMap.put("imagePath", "");
//							}else{
//								productAttrValue.setImagePath(productAttrValue.getImage());
//								valueMap.put("imagePath", "");
//							}
//						}else{
//							valueMap.put("imagePath", "");
//						}
                        valueMap.put("price", productAttrValue.getPrice());
                        valueMap.put("cost", productAttrValue.getCost());
                        valueMap.put("otPrice", productAttrValue.getOtPrice());
                        valueMap.put("stock", productAttrValue.getStock());
                        valueMap.put("singleCount", productAttrValue.getSingleCount());
//						valueMap.put("barCode", productAttrValue.getBarCode());
//						valueMap.put("weight", productAttrValue.getWeight());
//						valueMap.put("volume", productAttrValue.getVolume());
//						valueMap.put("brokerage", productAttrValue.getBrokerage());
//						valueMap.put("brokerageTwo", productAttrValue.getBrokerageTwo());
//						valueMap.put("pinkPrice", productAttrValue.getPinkPrice());
//						valueMap.put("pinkStock", productAttrValue.getPinkStock());

                        valueMapList.add(ObjectUtil.clone(valueMap));
                    }else{
                        if(isReset == 1){
                            valueMapList.add(ObjectUtil.clone(valueMap));
                        }
                    }
                }else{
                    valueMapList.add(ObjectUtil.clone(valueMap));
                }
            }

            this.addMap(headerMap, headerMapList, align, isActivity);

            resultMap.put("attr", fromatDetailDTOList);
            resultMap.put("value", valueMapList);
            resultMap.put("header", headerMapList);

        }catch (Exception e){
            e.printStackTrace();
        }
        return resultMap;
    }

    /**
     * 组合规则属性算法
     *
     * @param fromatDetailDTOList
     * @return DetailDto
     */
    private DetailDto attrFormat(List<FromatDetailDto> fromatDetailDTOList) {

        List<String> data = new ArrayList<>();
        List<Map<String, Map<String, String>>> res = new ArrayList<>();

        fromatDetailDTOList.stream().map(FromatDetailDto::getDetail)
            .forEach(i -> {
                if (i == null || i.isEmpty()) {
                    throw new YshopException("请至少添加一个规格值哦");
                }
                String str = ArrayUtil.join(i.toArray(), ",");
                if (str.contains("-")) {
                    throw new YshopException("规格值里包含'-',请重新添加");
                }
            });

        if (fromatDetailDTOList.size() > 1) {
            for (int i = 0; i < fromatDetailDTOList.size() - 1; i++) {
                if (i == 0) {
                    data = fromatDetailDTOList.get(i).getDetail();
                }
                List<String> tmp = new LinkedList<>();
                for (String v : data) {
                    for (String g : fromatDetailDTOList.get(i + 1).getDetail()) {
                        String rep2 = "";
                        if (i == 0) {
                            rep2 = fromatDetailDTOList.get(i).getValue() + "_" + v + "-"
                                + fromatDetailDTOList.get(i + 1).getValue() + "_" + g;
                        } else {
                            rep2 = v + "-"
                                + fromatDetailDTOList.get(i + 1).getValue() + "_" + g;
                        }

                        tmp.add(rep2);

                        if (i == fromatDetailDTOList.size() - 2) {
                            Map<String, Map<String, String>> rep4 = new LinkedHashMap<>();
                            Map<String, String> reptemp = new LinkedHashMap<>();
                            for (String h : rep2.split("-")) {
                                List<String> rep3 = Arrays.asList(h.split("_"));
                                if (rep3.size() > 1) {
                                    reptemp.put(rep3.get(0), rep3.get(1));
                                } else {
                                    reptemp.put(rep3.get(0), "");
                                }
                            }
                            rep4.put("detail", reptemp);

                            res.add(rep4);
                        }
                    }

                }

                if (!tmp.isEmpty()) {
                    data = tmp;
                }
            }
        } else {
            List<String> dataArr = new ArrayList<>();
            for (FromatDetailDto fromatDetailDTO : fromatDetailDTOList) {
                for (String str : fromatDetailDTO.getDetail()) {
                    Map<String, Map<String, String>> map2 = new LinkedHashMap<>();
                    dataArr.add(fromatDetailDTO.getValue() + "_" + str);
                    Map<String, String> map1 = new LinkedHashMap<>();
                    map1.put(fromatDetailDTO.getValue(), str);
                    map2.put("detail", map1);
                    res.add(map2);
                }
            }
            String s = StrUtil.join("-", dataArr);
            data.add(s);
        }

        DetailDto detailDto = new DetailDto();
        detailDto.setData(data);
        detailDto.setRes(res);

        return detailDto;
    }


    /**
     * 增加表头
     *
     * @param headerMap     headerMap
     * @param headerMapList headerMapList
     * @param align         align
     */
    private void addMap(Map<String, Object> headerMap, List<Map<String, Object>> headerMapList, String align, boolean isActivity) {
//		headerMap.put("title", "图片");
//		headerMap.put("slot", "pic");
//		headerMap.put("align", align);
//		headerMap.put("minWidth", 80);
//		headerMapList.add(ObjectUtil.clone(headerMap));

        headerMap.put("title", "售价");
        headerMap.put("slot", "price");
        headerMap.put("align", align);
        headerMap.put("minWidth", 120);
        headerMapList.add(ObjectUtil.clone(headerMap));

//		headerMap.put("title", "成本价");
//		headerMap.put("slot", "cost");
//		headerMap.put("align", align);
//		headerMap.put("minWidth", 120);
//		headerMapList.add(ObjectUtil.clone(headerMap));

        headerMap.put("title", "原价");
        headerMap.put("slot", "otPrice");
        headerMap.put("align", align);
        headerMap.put("minWidth", 120);
        headerMapList.add(ObjectUtil.clone(headerMap));

        headerMap.put("title", "库存");
        headerMap.put("slot", "stock");
        headerMap.put("align", align);
        headerMap.put("minWidth", 120);
        headerMapList.add(ObjectUtil.clone(headerMap));

        headerMap.put("title", "每份数量");
        headerMap.put("slot", "singleCount");
        headerMap.put("align", align);
        headerMap.put("minWidth", 120);
        headerMapList.add(ObjectUtil.clone(headerMap));


//		headerMap.put("title", "产品编号");
//		headerMap.put("slot", "barCode");
//		headerMap.put("align", align);
//		headerMap.put("minWidth", 120);
//		headerMapList.add(ObjectUtil.clone(headerMap));

//		headerMap.put("title", "重量(KG)");
//		headerMap.put("slot", "weight");
//		headerMap.put("align", align);
//		headerMap.put("minWidth", 120);
//		headerMapList.add(ObjectUtil.clone(headerMap));
//
//		headerMap.put("title", "体积(m³)");
//		headerMap.put("slot", "volume");
//		headerMap.put("align", align);
//		headerMap.put("minWidth", 120);

//		if (isActivity) {
//			headerMap.put("title", "拼团价");
//			headerMap.put("slot", "pinkPrice");
//			headerMap.put("align", align);
//			headerMap.put("minWidth", 120);
//			headerMapList.add(ObjectUtil.clone(headerMap));
//
//			headerMap.put("title", "拼团活动库存");
//			headerMap.put("slot", "pink_stock");
//			headerMap.put("align", align);
//			headerMap.put("minWidth", 120);
//			headerMapList.add(ObjectUtil.clone(headerMap));
//		}

        headerMap.put("title", "操作");
        headerMap.put("slot", "action");
        headerMap.put("align", align);
        headerMap.put("minWidth", 70);
        headerMapList.add(ObjectUtil.clone(headerMap));
    }
}
